﻿using com.iot.core.ext;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System.Globalization;

namespace com.iot.core.util
{
    public class MyJSON
    {
        static Newtonsoft.Json.JsonSerializer json = null;
        static MyJSON()
        {
            Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
            setting.ContractResolver = new LowercaseContractResolver();
            setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            setting.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;

            //日期类型默认格式化处理
            setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
            setting.DateFormatString = DateUtil.DateFormatString;

            ////空值处理
            setting.NullValueHandling = NullValueHandling.Include;

            setting.Formatting= Formatting.Indented; //空格
         
            var mylong = new MyLongConvert();
            setting.Converters.Add(mylong);

            ////高级用法九中的Bool类型转换 设置
            ////setting.Converters.Add(new BoolConvert("是,否"));
            ///
            JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
            {
                 
                return setting;
            });
             
        }

        public static string ToJSONString(Object obj)
        {
             
            string result = Newtonsoft.Json.JsonConvert.SerializeObject(obj);   
            return result;
        }

        public static T Parse<T>(string jsonText)
        { 
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonText);
             
        }

    }


    public class LowercaseContractResolver : DefaultContractResolver
    { 
        protected override string ResolvePropertyName(string propertyName)
        {
            return propertyName.ToLowerCamelCase();
        }

    }
    
    public class MyLongConvert : JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken jt = JValue.ReadFrom(reader);

            return jt.Value<long>();
        }


        public override bool CanConvert(Type objectType)
        {
            return typeof(long).Equals(objectType);
        }


        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value.ToString());
        }


    }


}
